package com.cloud.demo2020.config;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Configuration
@RefreshScope
public class GuavaConfig {

    private int x;
    private int y;
    public static Map<String, Object> configMap = new HashMap<>();

    @Value("${cloud.x}")
    public void setX(int x) {
        this.x = x;
        configMap.put("x", x);
    }

    @Value("${cloud.y}")
    public void setY(int y) {
        this.y = y;
        configMap.put("y", y);
    }

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Bean
    LoadingCache<String, RateLimiter> guavaCache() {
        return CacheBuilder.newBuilder()
                .maximumSize(1000)
                .expireAfterWrite(1, TimeUnit.DAYS)
                .build(new CacheLoader<String, RateLimiter>() {
                    @Override
                    public RateLimiter load(String key) {
                        // X分钟的X，Y上限的Y
                        /**
                         * x为分钟数, 必须乘以60
                         * 如果y为60, x为1*60, 则每秒钟只允许一个ip访问一次接口。
                         */
                        double rate = y / (x * 60);
                        return RateLimiter.create(rate);
                    }
                });
    }

}
